﻿/* ********************************************************************************
 * 名称：SysRole_DomainService
 * 描述：系统角色表  领域服务接口实现类（本类通过CodeSmith软件生成生成）
 * 创建人：HFL
 * 创建日期：2020-06-01 17:48:55
 * 修改人：
 * 修改日期：
 * *******************************************************************************/
using WPay.Domain.Base;
using WPay.Domain.Model.DTOs;
using WPay.Domain.Model.Entities;
using WPay.Domain.MainModule.Interface.DomainServices;
using WPay.Domain.MainModule.Interface.RepositoryServices;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using WPay.Infrastructure.Unity;
using System.Linq;
using Model.DTO.Manager;

namespace WPay.Domain.MainModule
{
    /// <summary>
    /// 系统角色表 领域服务接口实现类
    /// </summary>
    public class SysRole_DomainService : ISysRole_DomainService
    {

        /// <summary>
        /// 系统角色表 领域服务接口
        /// </summary>
        private ISysRole_RepositoryService sysRole_RepositoryService;
        private IEfCore_RepositoryService _efCore_RepositoryService;
        private IMngrLog_DomainService _mngrLog_DomainService;
        /// <summary>
        /// 带参构造，用于IOC
        /// </summary>
        public SysRole_DomainService(ISysRole_RepositoryService _sysRole_RepositoryService,
            IEfCore_RepositoryService efCore_RepositoryService, IMngrLog_DomainService mngrLog_DomainService)
        {
            sysRole_RepositoryService = _sysRole_RepositoryService;
            _efCore_RepositoryService = efCore_RepositoryService;
            _mngrLog_DomainService = mngrLog_DomainService;
        }


        #region 由软件生成，禁止修改，若需要扩展，请在下方进行扩展

        /// <summary>
        /// 根据主键获取系统角色表资料信息
        /// </summary>
        /// <param name="_iD"></param>
        /// <returns>返回单个系统角色表数据实体</returns>
        public SysRole Get(string _iD)
        {
            return this.sysRole_RepositoryService.Get(_iD);
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_cpnID">企业代码</param>
        /// <returns>返回系统角色表数据集合</returns>
        public List<SysRole> GetAll(string _cpnID)
        {
            return this.sysRole_RepositoryService.GetAll(_cpnID);
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <returns>返回系统角色表数据集合</returns>
        public List<SysRole> GetAll(Hashtable _param)
        {
            return this.sysRole_RepositoryService.GetAll(_param);
        }

        /// <summary>
        /// 按照分页条件查询数据集
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <param name="_pageIndex">查询页码，从1开始，必传</param>
        /// <param name="_pageSize">每页查询数据条数，必传</param>
        /// <param name="_sort">排序列名，若要降序请用列名+" DESC"，必传</param>
        /// <param name="_pageCount">返回总页码数</param>
        /// <param name="_dataCount">返回总数据条数</param>
        /// <returns>返回系统角色表数据集合</returns>
        public List<SysRole> GetByPage(Hashtable _param, int _pageIndex, int _pageSize, string _sort, out int _pageCount, out int _dataCount)
        {
            return this.sysRole_RepositoryService.GetByPage(_param, _pageIndex, _pageSize, _sort, out _pageCount, out _dataCount);
        }

        /// <summary>
        /// 插入系统角色表数据
        /// </summary>
        /// <param name="_sysRole">需要插入的系统角色表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(SysRole _sysRole)
        {
            return this.sysRole_RepositoryService.Add(_sysRole);
        }

        /// <summary>
        /// 批量插入系统角色表数据
        /// </summary>
        /// <param name="_sysRoleList">需要插入的系统角色表数据集合</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(List<SysRole> _sysRoleList)
        {
            return this.sysRole_RepositoryService.Add(_sysRoleList);
        }

        /// <summary>
        /// 根据主键更新系统角色表数据
        /// </summary>
        /// <param name="_sysRole">需要更新的系统角色表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(SysRole _sysRole)
        {
            return this.sysRole_RepositoryService.Update(_sysRole);
        }

        /// <summary>
        /// 根据主键更新系统角色表指定字段
        /// </summary>
        /// <param name="_sysRole">需要更新的系统角色表数据实体</param>
        /// <param name="_updateProNames">需要更新的字段名</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(SysRole _sysRole, params string[] _updateProNames)
        {
            return this.sysRole_RepositoryService.Update(_sysRole, _updateProNames);
        }


        #endregion

        /*业务扩展代码*/
        #region 业务扩展代码
        public void AddRole(HttpRequest httpRequest, SysRole model, LoginUserDTO data)
        {
            List<SysModuleAction> moduleAction = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SysModuleAction>>(httpRequest.Form["moduleActions"]);
           
            if (string.IsNullOrEmpty(model.RoleName))
            {
                throw new UNException("请输入角色名称!");
            }
            if (model.OrderID < 0)
            {
                model.OrderID = 0;
            }
            model.CpnId = data.CpnId; 
            //新增角色
            if (string.IsNullOrEmpty(model.ID))
            {
                //Add
                var RoleActions = new List<SysRoleAction>();
               
                model.ID = Guid.NewGuid().ToString();
                if (moduleAction != null && moduleAction.Any())
                {
                    var oldIds = moduleAction.Select(y => y.ID);
                    var myold =
                       _efCore_RepositoryService.GetMany(
                            new DirectSpecification<SysModuleAction>(
                                x => oldIds.Contains(x.ID) && !x.IsDeleted));
                    var old = myold.Select(x => new { x.ModuleID, x.Weight })
                        .ToList();
                    if (old.Count() != moduleAction.Count)
                    {
                        throw new UNException("部分模块状态被更改,请刷新页面重试!");
                    }

                    old.GroupBy(x => x.ModuleID).ToList().ForEach(x =>
                    {
                        RoleActions.Add(new SysRoleAction()
                        {
                            ID = Guid.NewGuid().ToString(),
                            ModuleID = x.Key,
                            RoleID = model.ID,
                            Weight = x.Sum(y => y.Weight)
                        });
                    });
                   
                }
                _mngrLog_DomainService.AddMngrLog("添加角色", $"{model.RoleName}角色被添加");
                _efCore_RepositoryService.Add(model);
                _efCore_RepositoryService.AddBatch(RoleActions); 
            }
            else
            {
                //Edit
                var item = _efCore_RepositoryService.GetByKey<SysRole>(model.ID);
                var RoleActions = _efCore_RepositoryService.GetMany(new DirectSpecification<SysRoleAction>(x => x.RoleID == item.ID)).ToList();
                if (item == null || item.IsDeleted)
                {
                    throw new UNException("没有查询到该角色,请重试!");
                }
                item.Memo = model.Memo;
                item.OrderID = model.OrderID;
                item.RoleName = model.RoleName;
                item.ImageUrl = model.ImageUrl;

                if (moduleAction != null && moduleAction.Any())
                {
                    var oldIds = moduleAction.Select(y => y.ID);
                    var oldRoleActId = RoleActions.Select(x => new { x.ModuleID, x.ID });
                    var myold =
                       _efCore_RepositoryService.GetMany(
                            new DirectSpecification<SysModuleAction>(
                                x => oldIds.Contains(x.ID) && !x.IsDeleted));
                    var old = myold.Select(x => new { x.ModuleID, x.Weight })
                        .ToList();
                    if (old.Count() != moduleAction.Count)
                    {
                        throw new UNException("部分模块状态被更改,请刷新页面重试!");
                    }
                    var roleActions = new List<SysRoleAction>();
                    old.GroupBy(x => x.ModuleID).ToList().ForEach(x =>
                    {
                        var oldroleaction = RoleActions.Where(y => y.ModuleID == x.Key);
                        oldroleaction.ToList().ForEach(y =>
                        {
                            y.Weight = x.Sum(z => z.Weight);
                            _efCore_RepositoryService.Update(y, z => z.Weight);
                        });
                        if (!RoleActions.Exists(y => y.ModuleID == x.Key))
                        {
                            roleActions.Add(new SysRoleAction()
                            {
                                ID = Guid.NewGuid().ToString(),
                                ModuleID = x.Key,
                                RoleID = model.ID,
                                Weight = x.Sum(y => y.Weight)
                            });
                        }
                    });
                    if (roleActions.Any())
                    {
                        _efCore_RepositoryService.AddBatch(roleActions);
                    }
                    var removeoldid =
                        oldRoleActId.Where(x => !old.Select(y => y.ModuleID).Contains(x.ModuleID)).Select(x => x.ID);
                    if (removeoldid != null && removeoldid.Any())
                    {
                        _efCore_RepositoryService.Remove(new DirectSpecification<SysRoleAction>(x => removeoldid.Contains(x.ID)));
                    }
                }
                else
                {
                    var removeid = RoleActions.Select(x => x.ID);
                    if (removeid != null && removeid.Any())
                    {
                        _efCore_RepositoryService.Remove(
                            new DirectSpecification<SysRoleAction>(x => removeid.Contains(x.ID)));
                    }
                }
             
                _efCore_RepositoryService.Update(item, x => x.Memo, x => x.OrderID, x => x.RoleName);
                _mngrLog_DomainService.AddMngrLog("修改角色", $"{model.RoleName}角色被修改");
            }
         
            _efCore_RepositoryService.SaveChanges();
        }

        public IEnumerable<string> DelRole(HttpRequest httpRequest)
        {
            var ids = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(httpRequest.Form["delds"]);
            var sysyrole = "1cce4cc6-3889-42eb-8b09-74f475480ac6";
            if (ids.Contains(sysyrole))
            {
                throw new UNException("所选角色包含系统超级管理员角色，无法删除");
            }
            if (ids.Any())
            {
                if ((sysRole_RepositoryService.ExistsRoleByRoleId(ids)))
                {
                    throw new UNException("当前角色下有管理账号存在,请先删除账号再删除角色!");
                }
                else
                {
                    _efCore_RepositoryService.LogicDelete(
                         new DirectSpecification<SysRole>(x => ids.Contains(x.ID)));
                
                    var names = (
                      _efCore_RepositoryService.GetMany(new DirectSpecification<SysRole>(x => ids.Contains(x.ID)))
                        ).Select(x => x.RoleName);
                    _mngrLog_DomainService.AddMngrLog("删除角色", $"{string.Join(",", names)}角色被删除");

                    _efCore_RepositoryService.SaveChanges();
                    return names;
                }

            }
            else
            {
                throw new UNException("请至少选择一个角色!");
            }

        }
        #endregion
    }
}
